package com.nf.health.app.datamain.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.RegisterNickActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.BluetoothDeviceNameAdapter;
import com.nf.health.app.customview.BoothDeviceDialog;
import com.nf.health.app.customview.BrokenLine;
import com.nf.health.app.models.BralectModel;
import com.nf.health.app.models.DataDetailExtra;
import com.nf.health.app.models.DataDetails;
import com.nf.health.app.models.Sleep;
import com.nf.health.app.models.SportBracelet;
import com.nf.health.app.models.SubSleepTemp;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.BigDecimalUtils;
import com.nf.health.app.utils.ByteUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.bluetools.BluetoothLeService;
import cn.bluetools.Pedometer_TypeInfo;
import cn.bluetools.ProtocolParser;
import cn.bluetools.SleepsData;
import cn.bluetools.SportsData;

@SuppressLint({"NewApi", "DefaultLocale"})
public class HealthyBraceletActivity extends BaseActivity {
    private static final String FLAG_BRACELET = "braceletHistory";
    private static final String FLAG_UPLOAD_SPORT = "flag_request_upload_sport_date";
    private static final String FLAG_UPLOAD_SLEEP = "glag_request_upload_sleep_data";

    protected static final String TAG = HealthyBraceletActivity.class.getSimpleName();
    private static final int SCAN_TIMEOUT = 10001; // 超时消息
    private static final int SCAN_MAXTIME = 30 * 1000; // 广播扫描的时间

    public static final int TYPE_SET_SETP_GOAL = 1;
    public static final int TYPE_SET_CALORIE_GOAL = 2;
    public static final int TYPE_SET_DISTANCE_GOAL = 3;
    public static final int TYPE_SET_SLEEP_GOAL = 4;
    public static final int TYPE_BIND = 5;
    public static final int TYPE_CONNECT = 6;
    protected static final int AUTO_CONNECT = 10002;
    private static final int CLISEREFRESHED = 100312;

    private LocalBroadcastManager localBroadcastManager;
    private BluetoothAdapter adapter;
    private BluetoothLeService mBluetoothLeService = MyApplication.mBluetoothLeService; // 蓝牙服务类
    private ServiceConnection mServiceConnection = MyApplication.mServiceConnection;
    /**
     * BLE扫描回调结果 蓝牙扫描过程不是每次通讯前的必须操作步骤，如果已有蓝牙设备的MAC地址，无需再进行扫描步骤
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback;

    private List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
    private MyHandler mHandler = new MyHandler(this);

    //避免出现内存溢出，使用静态内部类，引用context为弱引用
    public static class MyHandler extends Handler {
        private WeakReference<Context> weakReference;

        public MyHandler(Context context) {
            weakReference = new WeakReference<Context>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            HealthyBraceletActivity act = (HealthyBraceletActivity) weakReference.get();
            switch (msg.what) {
                case SCAN_TIMEOUT:
                    try {
                        act.scanBLE(false); // 停止扫描
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case AUTO_CONNECT:
                    // 绑定后再次进入自动连接
                    if (act.mBluetoothLeService != null && BluetoothLeService.isConnected) {
                        act.mBluetoothLeService.getSportDataTotal();//如果已经是绑定成功，直接获取手环中当前数据并显示
                    } else {
                        act.showLoading("连接中...");
                        act.currentType = TYPE_CONNECT;
                        String currentDeviceName = PreferenceHelper.getString(PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, "");
                        if (act.mBluetoothLeService != null) {
                            act.mBluetoothLeService.connect(currentDeviceName, "");
                        }
                    }
                    break;
                case CLISEREFRESHED:
                    mPullRefreshScrollView.onRefreshComplete();
                    break;
                default:
                    break;
            }

        }
    }

    private boolean isScanning = false; // 是否在扫描状态
    private PopupWindow popMore;
    private boolean isShowPopMore = false;
    TextView tv_bluetooth;
    ListView listview;
    private BluetoothDeviceNameAdapter sAdapter;

    private String calorie = "0";
    private String steps = "0";
    private String sleep = "0";
    private String kilometer = "0.00";

    private RadioGroup rg_bracelet_navigator;
    private TextView tv_type_name;
    private TextView tv_type_value;
    private ImageView iv_type_icon;


    private List<DataDetails> dataDetailsList = new ArrayList<DataDetails>();//获取历史数据的集合 --->>自己后台获取
    public static ArrayList<Float> yValue;
    private TextView tv_unit;
    private LinearLayout rl_broken_line;
    private ArrayList<String> xValues;
    private ArrayList<String> yValues;
    /**
     * 标记TAB
     */
    private int currentIndex = 0;//4个按钮点击切换的标志
    /**
     * 标记当前的操作类型，绑定，连接等
     */
    private int currentType = 0;//蓝牙连接的当前类型 （已断开 已连接 正在连接 ...）
    private int position;

    private String pageno = "1";
    private String pagesize = "15";
    private TextView tv_tab_steps;
    private TextView tv_tab_distance;
    private TextView tv_tab_sleep;
    private TextView tv_tab_calorie;
    private TextView tv_device_name;
    private TextView tv_bind_state;
    private TextView tv_loadl_input;
    private TextView tv_time;
    private TextView tv_goal;
    private TextView tv_set_sleep;
    private TextView tv_remind;
    private LinearLayout ll_bind_device;
    private String deviceType;

    private TextView history_text;

    private ImageView titlebar_right_view;
    //private AlertDialog alertDialog;
    int choiceItem = 0; //12 24小时制的标志

    private List<SportsData> sportsDatas = new ArrayList<SportsData>();//存放运动历史数据
    private List<SleepsData> sleepsDatas = new ArrayList<SleepsData>();//存放睡眠历史数据
    private List<BralectModel> sportHistoryData = new ArrayList<BralectModel>();
    ;//存放上传失败的历史数据


    long lightDuration = 0;
    long deepDuration = 0;
    long wakeDuration = 0;//清醒时长
    private long sleepDuration;//睡眠时长
    String sleepDate;

    private String KEY_UPLOAD_SPORT_DATA_TIME = "uploadSportsTime";
    private double rate;//曲选图的比例系数
    private UserInfo user;//个人信息

    /**
     * 睡眠数据对象（上传使用）
     */
    private Sleep sleepData;
    private String goal;//设定 步数，距离，睡眠，卡路里 目标使用


    static PullToRefreshScrollView mPullRefreshScrollView;
    private BoothDeviceDialog boothDeviceDialog;//搜索到的蓝牙设备的Dialog

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.layout_common_header);
        setContent(R.layout.activity_health_bracelet);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "手环数据");

        //检测是否完善注册信息
        boolean registerInfoCompleted = PreferenceHelper.getBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE,false);
        if (!registerInfoCompleted){
            showToast("请完善注册信息");
            finish();
            Bundle bundle = new Bundle();
            bundle.putString("type", "123");//跟注册时一样的type
            ActivityUtils.showActivity(this, RegisterNickActivity.class,bundle);
        }

        goal = PreferenceHelper.getString(BraceletGoalActivity.KEY_STEP_GOAL, "7000");

        String deviceName = getIntent().getStringExtra("deviceName");
        deviceType = getIntent().getStringExtra("deviceType");

        initView();
        // initMorePop();
        // initPop();
        try {
            initBlueTooth();
        } catch (Exception e) {
        }

        initData();

        //线形图  group  实例化
        provider.requestDataDetailsnew2(deviceType,"column" ,pageno, pagesize, FLAG_BRACELET);

    }

    private void initData() {
        user = PreferenceHelper.getUser();
        rate = 0.415;
        if ("0".equals(user.getSex())) {
            rate = 0.413;
        }

        String value = PreferenceHelper.getString("currentData", "0@0@0");
        sleep = PreferenceHelper.getString("currentSleepData", "0");
        String[] valueArray = value.split("@");
        tv_type_value.setText(valueArray[0] + "步");
        steps = valueArray[0];
        kilometer = valueArray[1];
        calorie = valueArray[2];
        tv_tab_steps.setText(valueArray[0]);
        tv_tab_distance.setText(valueArray[1]);
        tv_tab_calorie.setText(valueArray[2]);
        tv_tab_sleep.setText(sleep);
        initShowDialog();
        startConnectBooth(false);
        refreshView(currentIndex);
        ;//初始默认选中第一个
    }

    private void initMorePop() {
        if (popMore == null) {
            popMore = new PopupWindow(this);
            View view = View.inflate(getApplicationContext(), R.layout.pop_more, null);
            popMore.setContentView(view);
            popMore.setWidth(DensityUtil.dip2px(this, 150));
            popMore.setHeight(DensityUtil.dip2px(this, 300));
            ll_bind_device = ViewUtil.getView(view, R.id.ll_bind_device);

            tv_remind = ViewUtil.getView(view, R.id.tv_remind);
            tv_goal = ViewUtil.getView(view, R.id.tv_goal);
            tv_set_sleep = ViewUtil.getView(view, R.id.tv_set_sleep);
            tv_time = ViewUtil.getView(view, R.id.tv_time);

            tv_device_name = ViewUtil.getView(view, R.id.tv_device_name);
            tv_bind_state = ViewUtil.getView(view, R.id.tv_bind_state);
            tv_loadl_input = ViewUtil.getView(view, R.id.tv_loadl_input);

        }
        popMore.setFocusable(true);
        popMore.setOutsideTouchable(true);
        popMore.setBackgroundDrawable(new BitmapDrawable());
        popMore.setAnimationStyle(android.R.style.Animation_Dialog); // 0表示没有动画
        popMore.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                isShowPopMore = false;
            }
        });
        if (PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false)) {
            tv_device_name.setVisibility(View.VISIBLE);
            tv_bind_state.setText("取消绑定");
            tv_device_name.setText(PreferenceHelper.getString(PreferenceHelper.BLUETOOTH_DEVICE_NAME, ""));

            ll_bind_device.setOnClickListener(this);
            tv_remind.setOnClickListener(this);
            tv_goal.setOnClickListener(this);
            tv_time.setOnClickListener(this);
            tv_set_sleep.setOnClickListener(this);
            tv_loadl_input.setOnClickListener(this);

            int color = getResources().getColor(R.color.black9);
            tv_remind.setTextColor(color);
            tv_goal.setTextColor(color);
            tv_time.setTextColor(color);
            tv_set_sleep.setTextColor(color);
        } else {
            tv_device_name.setVisibility(View.GONE);
            tv_bind_state.setText("绑定设备");

            ll_bind_device.setOnClickListener(this);
            tv_loadl_input.setOnClickListener(this);
            tv_remind.setOnClickListener(null);
            tv_goal.setOnClickListener(null);
            tv_time.setOnClickListener(null);
            tv_set_sleep.setOnClickListener(null);
            int color = getResources().getColor(R.color.black8);
            tv_remind.setTextColor(color);
            tv_goal.setTextColor(color);
            tv_time.setTextColor(color);
            tv_set_sleep.setTextColor(color);
        }
    }

    private void initView() {
        tv_unit = (TextView) findViewById(R.id.tv_unit);
        rl_broken_line = (LinearLayout) findViewById(R.id.rl_broken_line);
        //		yValues = new ArrayList<String>();
        //		xValues = new ArrayList<String>();
        yValue = new ArrayList<Float>();

        history_text = ViewUtil.getView(this, R.id.history_text);

        tv_bluetooth = ViewUtil.getView(this, R.id.tv_bluetooth);
        //直接设置监听而不是特殊条件才进行监听
        tv_bluetooth.setOnClickListener(this);
        iv_type_icon = ViewUtil.getView(this, R.id.iv_type_icon);
        tv_type_name = ViewUtil.getView(this, R.id.tv_type_name);
        tv_type_value = ViewUtil.getView(this, R.id.tv_type_value);

        tv_tab_steps = ViewUtil.getView(this, R.id.tv_tab_steps);
        tv_tab_distance = ViewUtil.getView(this, R.id.tv_tab_distance);
        tv_tab_sleep = ViewUtil.getView(this, R.id.tv_tab_sleep);
        tv_tab_calorie = ViewUtil.getView(this, R.id.tv_tab_calorie);

        rg_bracelet_navigator = ViewUtil.getView(this, R.id.rg_bracelet_navigator);

        titlebar_right_view = ViewUtil.getView(this, R.id.titlebar_right_view);
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);

        titlebar_right_view.setOnClickListener(this);
        tv_bluetooth.setOnClickListener(this);
        rg_bracelet_navigator
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {


                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.rb_steps:
                                currentIndex = 0;
                                iv_type_icon.setImageResource(R.drawable.ic_steps);
                                tv_type_name.setText("步数");
                                tv_type_value.setText(steps + "步");
                                goal = PreferenceHelper.getString(BraceletGoalActivity.KEY_STEP_GOAL, "7000");
                                break;
                            case R.id.rb_distance:
                                currentIndex = 1;
                                iv_type_icon.setImageResource(R.drawable.ic_distance);
                                goal = PreferenceHelper.getString(BraceletGoalActivity.KEY_DISTANCE_GOAL, "5");
                                tv_type_name.setText("距离");
                                tv_type_value.setText(kilometer + "公里");
                                break;
                            case R.id.rb_sleep:
                                currentIndex = 2;
                                iv_type_icon.setImageResource(R.drawable.ic_sleep);
                                goal = PreferenceHelper.getString(BraceletGoalActivity.KEY_SLEEP_GOAL, "8");
                                tv_type_name.setText("睡眠");
                                tv_type_value.setText(sleep + "小时");
                                break;
                            case R.id.rb_calorie:
                                currentIndex = 3;
                                iv_type_icon
                                        .setImageResource(R.drawable.ic_calorie);
                                goal = PreferenceHelper.getString(BraceletGoalActivity.KEY_CALORIES_GOAL, "350");
                                tv_type_name.setText("卡路里");
                                tv_type_value.setText(calorie + "千卡");
                                break;
                        }
                        refreshView(currentIndex);
                    }
                });

        history_text.setOnClickListener(new View.OnClickListener() {//历史记录

            @Override
            public void onClick(View arg0) {
                ActivityUtils.showActivity(HealthyBraceletActivity.this, HistoryWristActivity.class);
                //历史记录所需参数
            }
        });

        mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        mPullRefreshScrollView.setMode(Mode.PULL_FROM_START);
        mPullRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //TODO
                startConnectBooth(true);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view:
                if (!isShowPopMore) {
                    initMorePop();
                    popMore.showAsDropDown(titlebar_right_view);
                    isShowPopMore = true;
                }
                // scanBLE(true);
                break;
            case R.id.ll_bind_device:
                if (!adapter.isEnabled()) {//进行蓝牙连接
                    adapter.enable();
                /*Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(mIntent, 1);*/

                }
                popMore.dismiss();
                SystemClock.sleep(1000);//睡眠,保证蓝牙就绪
                if (PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false)) {
                    cancelBind();
                } else {
                    // 搜索设备并绑定
                    devices.clear();
                    scanBLE(false);
                    scanBLE(true);
                    //showDialog();
                }
                break;
            case R.id.tv_remind:
                popMore.dismiss();
                ActivityUtils.showActivity(this, BraceletRemindActivity.class);
                break;
            case R.id.tv_goal:
                popMore.dismiss();
                ActivityUtils.showActivity(this, BraceletGoalActivity.class);
                break;
            case R.id.tv_set_sleep:
                popMore.dismiss();
                ActivityUtils.showActivity(this, BraceletSleepActivity.class);
                break;
            case R.id.tv_loadl_input:
                ActivityUtils.showActivity(HealthyBraceletActivity.this, MyShopStoreActivity.class);
//                ActivityUtils.showActivity(HealthyBraceletActivity.this, LoadWebHealthyDataActivty.class);
                break;
            case R.id.tv_time:
                popMore.dismiss();
                if (PreferenceHelper.getBoolean(PreferenceHelper.IS24H, false)) {
                    choiceItem = 1;
                }
                new AlertDialog.Builder(this).setTitle("时间格式")
                        .setSingleChoiceItems(new String[]{"12小时", "24小时"}, choiceItem, listener)
                        .setPositiveButton("确定", listener)
                        .setNegativeButton("取消", null).show();
                break;

            case R.id.tv_bluetooth:
               /* List<BralectModel> sportList = PreferenceHelper.getFaildBraceletHisrySportData1();
                if (sportList != null) {
                    for (int i = 0; i < sportList.size(); i++) {
                        LogUtil.e("yuyahao", sportList.get(i) + "");
                    }
                }

                List<SleepsData> sleepList = PreferenceHelper.getFaildBraceletSleepData1();
                if (sleepList != null) {
                    for (int i = 0; i < sleepList.size(); i++) {
                        LogUtil.e("yuyahao", DateUtil.date2String(sleepList.get(i).time_stamp * 1000, "yyyy-MM-dd HH:mm:ss") + "----->" + sleepList.get(i).status + "--->" + sleepList.get(i).time_stamp);
                    }
                }
                parseListSleepsDataAndUopload(sleepList);*/
                if (!adapter.enable()) {
                    showToast("蓝牙关闭");
                    return;
                }
                if (!adapter.isEnabled()) {//进行蓝牙连接
                    adapter.enable();
				/*Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(mIntent, 1);*/
                }
                if (PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false)) {//已经绑定,则进行取消绑定
                    //cancelBind();
                } else {// 搜索设备并绑定
                    devices.clear();
                    scanBLE(false);
                    scanBLE(true);
                    //showDialog();
                }
                break;

            default:
                break;
        }
    }

    /**
     * 取消绑定
     * <li>清空蓝牙名称，地址等数据
     * <li>重置UI
     * <li>蓝牙服务关闭
     */
    private void cancelBind() {
        PreferenceHelper.putBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false);
        PreferenceHelper.putString(PreferenceHelper.BLUETOOTH_DEVICE_NAME, "");
        PreferenceHelper.putString(PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, "");

        PreferenceHelper.putString("currentData", "0@0@0");//以@间隔的形式存储步数，距离和卡路里
        PreferenceHelper.putString("currentSleepData", "0");
        sleep = calorie = kilometer = steps = "0";
        resetTabValue();
        tv_bluetooth.setText("(未连接)");
        hideLoading();

        mBluetoothLeService.real_close();
        mPullRefreshScrollView.onRefreshComplete();
        //关掉设备蓝牙
        if (adapter != null) {
            adapter.disable();
        }
        isScanning = false;
    }

    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int witch) {
            switch (witch) {
                case AlertDialog.BUTTON_POSITIVE: //点击确认后，获取选中的信息
                    if (choiceItem == 0) {
                        PreferenceHelper.putBoolean(PreferenceHelper.IS24H, false);
                    } else {
                        PreferenceHelper.putBoolean(PreferenceHelper.IS24H, true);
                    }
                    if (mBluetoothLeService != null && BluetoothLeService.isConnected) {
                        mBluetoothLeService.setTimeType(PreferenceHelper.getBoolean(PreferenceHelper.IS24H, false), true, false, false, 0);
                    } else {
                        showToast("蓝牙已断开");
                    }
                    break;
                default:
                    choiceItem = witch;
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService();
    }

    /**
     * 取消绑定蓝牙服务和广播
     */
    public void unbindService() {
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        if (localBroadcastManager != null) {
            localBroadcastManager.unregisterReceiver(mGattUpdateReceiver);
        }
        //禁止关掉手环蓝牙
		/*if (adapter != null) {
			adapter.disable();
		}*/
        mBluetoothLeService = null;
    }

    /**
     * @param enable true:开启扫描 false: 停止扫描
     */
    private void scanBLE(boolean enable) {
        if (enable) {
            if (isScanning)
                return; // 正在扫描状态退出
            adapter.startLeScan(mLeScanCallback);
            isScanning = true;
            mHandler.sendEmptyMessageDelayed(SCAN_TIMEOUT, SCAN_MAXTIME);
        } else {
            adapter.stopLeScan(mLeScanCallback); // 停止扫描
            isScanning = false;
        }

    }

    private void initBlueTooth() {
        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙通讯");
            finish();
            return;
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            showToast("设备不支持蓝牙");
            finish();
            return;
        }

        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

            @SuppressLint("NewApi")
            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi,
                                 byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != device.getName() && device.getName().startsWith("L28")) {
                            LogUtil.e("yuyahao", device.getName());
                            if (!devices.contains(device)) {
                                devices.add(device);
                                if (sAdapter == null) {
                                    sAdapter = new BluetoothDeviceNameAdapter(listview, devices, R.layout.show_item);
                                } else {
                                }
                                listview.setAdapter(sAdapter);
                                sAdapter.notifyDataSetChanged();
                                if (devices.size() > 0) {
                                    if (boothDeviceDialog != null) {
                                        if (!boothDeviceDialog.isShowing()) {
                                            if (!isFinishing()) {
                                                boothDeviceDialog.show();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
        };
        if (!adapter.isEnabled()) {//进行蓝牙连接
            adapter.enable();
			/*Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(mIntent, 1);*/
        }
        bindLeService();
    }

    private void bindLeService() {
       /* mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                Constants.mBluetoothLeService = mBluetoothLeService;
                BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28T);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };*/

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
        localBroadcastManager.registerReceiver(mGattUpdateReceiver, BluetoothLeService.makeGattUpdateIntentFilter());
    }


    private void initShowDialog() {
        boothDeviceDialog = new BoothDeviceDialog(HealthyBraceletActivity.this);
        boothDeviceDialog.setCanceledOnTouchOutside(false);
        listview = boothDeviceDialog.getListview();
        boothDeviceDialog.setOnListItem(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
                scanBLE(false);
                if (devices.get(postion).getName().contains("T")) {
                    BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28T);
                } else if (devices.get(postion).getName().contains("S")) {
                    BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28S);
                }
                showLoading("绑定中...");
                currentType = TYPE_BIND;
                position = postion;
                mBluetoothLeService.connect(devices.get(postion).getAddress(), "");
                mHandler.removeMessages(SCAN_TIMEOUT);
                boothDeviceDialog.dismiss();
            }
        });
    }

    /**
     * 接收蓝牙服务传入的事件消息，或者是接收到的蓝牙数据
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                hideLoading();
                switch (currentType) {
                    case TYPE_BIND:
                        PreferenceHelper.putBoolean(PreferenceHelper.BLUETOOTH_IS_BING, true);
                        PreferenceHelper.putString(PreferenceHelper.BLUETOOTH_DEVICE_NAME, devices.get(position).getName());
                        PreferenceHelper.putString(PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, devices.get(position).getAddress());
                        showToast("绑定成功");
                        tv_bluetooth.setOnClickListener(HealthyBraceletActivity.this);
                        mBluetoothLeService.getWatchId();
                        setInitGoalValues();
                        break;
                    case TYPE_CONNECT:
                        mPullRefreshScrollView.onRefreshComplete();
                        mBluetoothLeService.getSportDataTotal();
                        break;
                }
                //重置当前type
                currentType = -1;
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_TIMEOUT.equals(action)) {
                // 蓝牙通讯超时，这里可以重发未响应的命令
                hideLoading();
                mPullRefreshScrollView.onRefreshComplete();
                tv_bluetooth.setText("(未连接)");
                showToast("蓝牙连接超时");
                setFlagBraceletNodata();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                // 蓝牙断开
                hideLoading();
                mPullRefreshScrollView.onRefreshComplete();
                /*showToast("取消绑定成功");
                showToast("取消绑定成功");*/
                setFlagBraceletNodata();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                // 接收到蓝牙数据
                hideLoading();
                mPullRefreshScrollView.onRefreshComplete();
                byte[] bytes = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                String s = ProtocolParser.bytes2HexString(bytes);
                LogUtil.d(TAG, "接收到数据:" + s + "\n");
                //System.out.println("接收到数据:" + s+ "\n");
                parseData(bytes);
                if (mBluetoothLeService != null && BluetoothLeService.isConnected) {
                    tv_bluetooth.setText("(已连接)");
                } else {
                    tv_bluetooth.setText("(未连接)");
                    setFlagBraceletNodata();
                }
            }
        }
    };


    protected void parseData(byte[] bytes) {
        if (null == bytes)
            return;
        if (bytes.length == 5 && bytes[2] == (byte) 0x00) {
            //显示电量
        } else if ((bytes.length == 6) && bytes[2] == 0x01) {
            parseCommandData(bytes);
        } else if (bytes.length == 9 && bytes[2] == 0x13) {
            parseSleepData(bytes);//获取睡眠历史数据
        } else if (bytes.length == 24 && bytes[2] == 0x04) {
            showDeviceWatchID(bytes);
            syncPersonData();
        } else if (bytes.length == 20 && bytes[2] == 0x0F) {
            // 获取运动数据完成，之后获取睡眠详情数据
            showSportDatas(bytes);
            provider.requestAddScore("12", "");//添加积分
            //获取运动历史数据
            mBluetoothLeService.getSportDataDetail();//获取数据第二条指令 ====>获取运动历史数据  第三条指令 getSleepDataDetail

        } else if ((bytes.length == 21 && bytes[2] == 0x05)// L28S/C返回
                || (bytes.length == 19 && bytes[2] == 0x05)) {// L11/L28T/W/H返回
            parseSportDetailData(bytes);
        }
    }

    /**
     * 解析一系列指令
     *
     * @param bytes
     */
    private void parseCommandData(byte[] bytes) {
        /*LogUtil.e("yuyahao", "parseCommandData历史数据bytes：   " + bytes);*/
        LogUtil.d(TAG, "解析数据 收到应答 ,命令码:  0x" + String.format("%02x", bytes[3]) + "     结果： " + showResult(bytes[4]) + "\n");
        switch (bytes[3]) {
            case 0x40: // 添加提醒返回
                break;
            case 0x0c: // 设置个人信息返回
                mBluetoothLeService.setSynTime();
                break;
            case 0x06: // 运动详细数据传输完成返回
                LogUtil.d(TAG, "获取运动详细数据完成\n");
                /**********syncUploadSports();***原来的上传数据的老接口方法**///获取历史数据完成 。上传历史数据（3个获取数据都已完成）
                /*if(!PreferenceHelper.isFistUploadSportData()){//如果是同一天
                }*/
                getSportListData();//上传历运动史数据（每次都同步）
                mBluetoothLeService.getSleepDataDetail();//然后在获取运动睡眠数据
                break;
            case 0x09: // 删除提醒返回
                break;
            case 0x15: // 时间时间返回
                //同步时间完成，之后设置时间格式。流程结束
                mBluetoothLeService.setTimeType(true, true, false, false, 0);
                break;
            case 0x31: // 睡眠命令返回
                if (!PreferenceHelper.isFistUploadsleepData()) {//如果是同一天
                    //showSleepData();//读取睡眠历史记录并显示
                    parseListSleepsDataAndUopload(sleepsDatas);//上传睡眠历史数据
                }
                //mBluetoothLeService.getSportDataDetail();//获取数据第二条指令 ====>获取运动历史数据  第三条指令 getSleepDataDetail
                break;
            case 0x32: // 设置自动删除数据模式返回
                LogUtil.d(TAG, "获取当日运动汇总\n");
                mBluetoothLeService.getSportDataTotal();//获取数据第一条指令 ====>获取当前的数据，（频繁调用）
                break;
            case 0x34: // 时间格式和距离单位设置的返回码
                //TODO
                mBluetoothLeService.getSportDataTotal();
                break;
            case 0x36:
                showToast("设置成功");
                break;
            case (byte) 0xa2://设置目标：卡路里和距离
            case 0x0d://设置步数
                showToast("设置成功");
                break;
            default:
                break;
        }
    }

    /**
     * 解析运行详细数据
     *
     * @param bytes
     */
    private void parseSportDetailData(byte[] bytes) {
        SportsData sData = ProtocolParser.parseSportDetailData(bytes);
        if (null == sData) {
            LogUtil.d(TAG, "获取运动详细数据为空\n");
        } else {
            LogUtil.d(TAG, "获取运动详细数据:  步数:" + sData.steps + " ,卡路里: " + sData.cal + " \n");
            sportsDatas.add(sData);//获取运动累死还是数据 后 ，开始执行上产运动历史数据
        }
    }

    /**
     * 显示睡眠时长
     */
    private void showSleepData() {
       /* if (sleepsDatas.size() <= 0) {
            return;
        }
        if (sleepsDatas.size() == 0) {
            sleep = 0.0 + "";
            return;
        } else if (sleepsDatas.size() >= 1) {
            sleep = new SubSleepTemp().getSleepHistoryOneDayDate(sleepsDatas);
        }
        resetTabValue();
        PreferenceHelper.putString("currentSleepData", sleep);*/
    }

    /**
     * 显示WatchID
     *
     * @param bytes
     */
    private void showDeviceWatchID(byte[] bytes) {
        /*********************/
        LogUtil.d(TAG, "获取的DN号为：" + ProtocolParser.parseDeviceDN(bytes) + "\n");
    }

    /**
     * 显示睡眠详情
     * 获取睡眠历史数据
     *
     * @param bytes
     */
    private void parseSleepData(byte[] bytes) {
        SleepsData sldata = ProtocolParser.parseSleepData(bytes);
        if (sldata != null) {
            //LogUtil.e("yuyahao", "睡眠历史数据：   " + sldata.status + ": 睡眠时长：" + DateUtil.date2String(sldata.time_stamp * 1000, "yyyy-MM-dd HH:mm:ss") + "   " + sldata.time_stamp * 1000);
        }
        if (sldata == null) {
        } else {
            if (bytes.length == 9) {
                if (sldata.status == 1) {//当前睡眠类型--睡着--
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 2) {//当前睡眠类型--浅睡--\n
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 3) {//当前睡眠类型--醒着--\n
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 4) {//当前睡眠类型--准备入睡--\n
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 5) {//当前睡眠类型--退出入睡--\n
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 6) {//当前睡眠类型--进入睡眠 模式(手动进 入) --\n
                    sleepsDatas.add(sldata);
                } else if (sldata.status == 7) {//当前睡眠类型--退出睡眠模式进入正常模式--\n
                    sleepsDatas.add(sldata);
                } else {
                    //出错了
                }
            }
        }
    }

    /*********
     * 上传睡眠历史数据
     *********/
    private void parseListSleepsDataAndUopload(List<SleepsData> sleepsDatas) {
        List<SleepsData> hostoryList = PreferenceHelper.getFaildBraceletSleepData();
        if (hostoryList != null) {//获取上次储存失败的历史数据
            if (sleepsDatas != null) {
                sleepsDatas.addAll(PreferenceHelper.getFaildBraceletSleepData());
            } else {
                sleepsDatas = hostoryList;
            }
        }
        if (sleepsDatas == null || sleepsDatas.size() == 0) {
            return;
        }
        //PreferenceHelper.saveFaildBraceletSleepData1(sleepsDatas);//提交时一定要注释掉该代码
        TreeMap<Long, List<List<SleepsData>>> dataPerdataMapList = new TreeMap<>();
        LinkedList<List<SleepsData>> dataLinkList = new SubSleepTemp().getSleepHistoryDataDetailList(sleepsDatas);
        long currentLongTime = 0l;
        List<List<SleepsData>> newSleepList = new ArrayList<List<SleepsData>>();
        //对同一天当中的数据进行添加到集合中去
        for (int i = 0; i < dataLinkList.size(); i++) {//进行遍历
            List<SleepsData> currentSleepData = dataLinkList.get(i);
            if (i == 0) {//去除第一个时间点，用第一个时间点进行比较，进行比较
                currentLongTime = dataLinkList.get(0).get(0).time_stamp;//将第一天的时间点取出来 作为作为第一天map集合的key值
            }
            if (DateUtil.isSameDayOfMillis(currentSleepData.get(0).time_stamp * 1000L, currentLongTime * 1000L)) {//是同一天 添加到临时集合中去
                newSleepList.add(currentSleepData);
                if (i == dataLinkList.size() - 1) {
                    if (dataPerdataMapList.containsKey(currentLongTime)) {
                        dataPerdataMapList.get(currentLongTime).addAll(newSleepList);
                    } else {
                        dataPerdataMapList.put(currentLongTime, newSleepList);
                    }
                }
            } else {//不是同一天，则对临时集合进行处理
                if (newSleepList.size() > 0) {  //临时集合大于 0 ，则添加到临时集合中去
                    if (dataPerdataMapList.containsKey(currentLongTime)) {
                        List<List<SleepsData>> subLastSleep = dataPerdataMapList.get(currentLongTime);
                        /*List<List<SleepsData>> newSleepList2 = new ArrayList<List<SleepsData>>();*/
                        subLastSleep.addAll(newSleepList);
                        /*newSleepList2.addAll(subLastSleep);
                        dataPerdataMapList.put(currentLongTime, newSleepList2);*/
                    } else {
                        List<List<SleepsData>> newSleepList2 = new ArrayList<List<SleepsData>>();
                        newSleepList2.addAll(newSleepList);
                        dataPerdataMapList.put(currentLongTime, newSleepList2);
                    }
                }
                newSleepList.clear();//清空临时集合
                currentLongTime = dataLinkList.get(i).get(0).time_stamp;//将不同一天的时间点去除来作为下次map集合的key值
                List<List<SleepsData>> newSleepList3 = new ArrayList<List<SleepsData>>();
                newSleepList3.add(currentSleepData);
                dataPerdataMapList.put(currentLongTime, newSleepList3);//将 比对第二次集合的的第一天的数据添加到map集合中去
            }
        }
        //储存key值
        ArrayList<Long> keyList = new ArrayList<Long>();
        Iterator<Map.Entry<Long, List<List<SleepsData>>>> it = dataPerdataMapList.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Long, List<List<SleepsData>>> entry = it.next();
            keyList.add(entry.getKey());
            // System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

        TreeMap<Long, List<List<SleepsData>>> dataPerdataMapList2 = new TreeMap<>();
        int index = 0;//遍历for循环的索引值
        for (Map.Entry<Long, List<List<SleepsData>>> entry : dataPerdataMapList.entrySet()) {
            long currentLongKey = entry.getKey();//取出时间值（状态为4的时间值）
            List<List<SleepsData>> lastSleepList = new ArrayList<>();
            List<List<SleepsData>> currentSleepList = new ArrayList<>();
            List<List<SleepsData>> list = entry.getValue();
            long currentUserKey = 0l;//代表需要用的有效long型的key
            long lastKey = 0l;//代表前一天的状态为4的值
            for (int i = 0; i < list.size(); i++) {
                long theFirstTime = list.get(i).get(0).time_stamp;//取得当前集合中的第一条的time值
                String ss = DateUtil.date2String(theFirstTime * 1000, "HH");
                if (DateUtil.isBigger12DotPotionTime(theFirstTime * 1000)) {//小于12点
                    currentSleepList.add(list.get(i));//向子集合中添加数据
                } else {
                    lastSleepList.add(list.get(i));
                }
            }
            long isLastDayLongTimel = currentLongKey - 24 * 60 * 60;//根据集合获取当天减去前一天的时间值（非集合中，得到实际前一天的long值，用于隔天，当天有小于12点的值）
            if (index == 0) {//index为0，说明为第一天，
                //顺序要邦正先后，当index 的size》0说明集合的第一天key有小于12点的数据，则先添加前一天的数据，后添加当天的数据
                if (lastSleepList.size() > 0) {//list为0，则，说明当前的数据全部小于12
                    dataPerdataMapList2.put(isLastDayLongTimel, lastSleepList);//添加前一天的数据
                }
                if (currentSleepList.size() > 0) {
                    currentUserKey = currentSleepList.get(0).get(0).time_stamp;
                    dataPerdataMapList2.put(currentUserKey, currentSleepList);//添加当天的数据
                    keyList.set(index, currentUserKey);//这一步非常关键，因为上传数据时需要有效的时间戳，重新给存放有效时间的集合赋值
                }
            } else {
                lastKey = keyList.get(index - 1);//index大于0时，去除存放 key的long型时间的上一个值，由于
                if (lastSleepList.size() > 0) {//有大于12点的数据即前一年的数据
                    //由于时间与可能不是连续型的，肯定要判断 lastkey 和当前的long型作比较
                    if (DateUtil.isSameDayOfMillis(lastKey * 1000, isLastDayLongTimel * 1000)) {//判断取得前一天的两个时间点是同一天
                        //根据上一天的key，取得上一天的集合
                        if (dataPerdataMapList2.containsKey(lastKey)) {//做异常判断，是否包含前一天key
                            List<List<SleepsData>> lastSleepLists = dataPerdataMapList2.get(lastKey);
                            //有大于12点的数据
                            lastSleepLists.addAll(lastSleepList);//是同一天向集合只能添加数据
                        } else {
                            dataPerdataMapList2.put(isLastDayLongTimel, lastSleepList);//是同一天向集合只能添加数据
                        }
                    } else {//不是同一天，说明map集合中没有前一天的历史记录，但是，当天有大于12点的，根据需求，小于12点的要设置为前一天的数据
                        if (lastSleepList.size() > 0) {//有大于于12点的数据
                            dataPerdataMapList2.put(isLastDayLongTimel, lastSleepList);//是同一天向集合只能添加数据
                        }
                    }
                }
                if (currentSleepList.size() > 0) {//有小于12点的数据
                    if (dataPerdataMapList2.containsKey(currentUserKey)) {
                        List<List<SleepsData>> currentDateList = dataPerdataMapList2.get(currentUserKey);
                        currentDateList.addAll(currentSleepList);//是同一天向集合只能添加数据
                    } else {
                        currentUserKey = currentSleepList.get(0).get(0).time_stamp;
                        keyList.set(index, currentUserKey);
                        dataPerdataMapList2.put(currentUserKey, currentSleepList);//是当天向集合只能添加数据
                    }
                }
            }
            index++;
        }
        /*Iterator<Map.Entry<Long, List<List<SleepsData>>>>  it2 = dataPerdataMapList2.entrySet().iterator();
        while (it2.hasNext()) {
            Map.Entry<Long, List<List<SleepsData>>> entry = it2.next();
            List<List<SleepsData>> getMapList = entry.getValue();
            LogUtil.e("yyh",entry.getKey()+"--------------------"+ DateUtil.date2String(entry.getKey() * 1000, "yyyy-MM-dd HH:mm:ss"));
            for(int i = 0 ; i < getMapList.size(); i++){
                List<SleepsData> list = getMapList.get(i);
                for (int j = 0; j < list.size(); j++) {
                    SleepsData sleepData = list.get(j);
                    LogUtil.e("yyh", DateUtil.date2String(sleepData.time_stamp * 1000, "yyyy-MM-dd HH:mm:ss") + "----->" + sleepData.status + "--->" +sleepData.time_stamp);
                }
            }
        }*/
        JSONArray jsonArray = new SubSleepTemp().getSleepHistoryJSONArray2(dataPerdataMapList2);
        sleep = PreferenceHelper.getString("currentSleepData","0");
        resetTabValue();
        String json = "";
        if (jsonArray.length() > 0) {//有数据，进行上传 ，睡眠
            json = jsonArray.toString();
            provider.addbraceletSleepData(json, FLAG_UPLOAD_SLEEP);
        }
    }


    //上传历史数据
    private void syncUploadSports() {
        for (int i = 0; i < sleepsDatas.size(); i++) {
            if (sleepsDatas.get(i).status == 2 && (sleepsDatas.get(i + 1).status == 1 || sleepsDatas.get(i + 1).status == 2)) {
                lightDuration += (sleepsDatas.get(i + 1).time_stamp - sleepsDatas.get((i)).time_stamp);
            }
            if (sleepsDatas.get(i).status == 1 && sleepsDatas.get(i + 1).status == 2) {
                deepDuration += (sleepsDatas.get(i + 1).time_stamp - sleepsDatas.get((i)).time_stamp);
            }
            if (sleepsDatas.get(i).status == 4 && sleepsDatas.get(i + 1).status == 2) {
                wakeDuration += (sleepsDatas.get(i + 1).time_stamp - sleepsDatas.get((i)).time_stamp);
            }
        }
        PreferenceHelper.saveFaildBraceletSleepData(sleepsDatas);
        if (sportsDatas.size() <= 0) {
            return;
        }
        List<SportBracelet> list = new ArrayList<SportBracelet>();
        long startTime = sportsDatas.get(0).time_stamp * 1000;
        int startSteps = sportsDatas.get(0).steps;
        int startCalories = sportsDatas.get(0).cal;

        if (sportsDatas.size() == 1) {
            addList(list, startTime, startSteps, startCalories);
        }

        for (int i = 1; i < sportsDatas.size(); i++) {
            if (DateUtil.isSameDayOfMillis(startTime, sportsDatas.get(i).time_stamp * 1000)) {
                startSteps += sportsDatas.get(i).steps;
                startCalories += sportsDatas.get(i).cal;

                if (i == sportsDatas.size() - 1) {
                    addList(list, startTime, startSteps, startCalories);
                }
            } else {
                // 直接使用startSteps，封装到集合中
                addList(list, startTime, startSteps, startCalories);

                if (DateUtil.isSameDayOfMillis(System.currentTimeMillis(), sportsDatas.get(i).time_stamp * 1000)) {
                    //如果当前的系统时间和时间戳是同一天，则不加入集合中
                    break;
                }
                // 重置startSteps
                startSteps = sportsDatas.get(i).steps;
                startCalories = sportsDatas.get(i).cal;
                startTime = sportsDatas.get(i).time_stamp * 1000;
            }
        }
        final String json = new Gson().toJson(list);

        //provider.uploadBraceletData(json, "synchronization");
    }

    private void addList(List<SportBracelet> list, long startTime, int startSteps, int startkll) {
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<String, Object>();
        String date = DateUtil.date2String(startTime, "yyyy-MM-dd");
        if (date.equals(sleepDate)) {
            sleepData = new Sleep("0", sleepDuration + "", wakeDuration + "", lightDuration + "", deepDuration + "", sleepDuration + "", "1", hashMap);
            for (SleepsData item : sleepsDatas) {
                hashMap.put(item.time_stamp + "", (item.status - 1) + "");
            }
        } else {
            sleepData = new Sleep("0", "0", "0", "0", "0", "0", "0", hashMap);
        }
        String distance = String.format("%.2f", startSteps * Double.parseDouble(PreferenceHelper.getUser().getHeight()) * rate / (100 * 1000));
        SportBracelet bracelet = new SportBracelet(date, (startkll / 1000) + "", startSteps + "", distance, sleepData);
        list.add(bracelet);
    }

    /**
     * 获取当前显示数据
     *
     * @param bytes
     */
    private void showSportDatas(byte[] bytes) {
        //  LogUtil.e("yuyahao", "运动历史数据bytes：   " + bytes);
        // 运动汇总数据返回
        SportsData sData = ProtocolParser.parseSportTotalData(bytes);
        //  LogUtil.e("yuyahao", "运动历史数据：   " + sData.cal + ": 时长：" + DateUtil.date2String(sData.time_stamp, "yyyy-MM-dd :") + " 步数： " + sData.steps);
        if (null == sData) {
            LogUtil.d(TAG, "获取运动汇总数据为空\n");
            return;
        } else {
            LogUtil.d(TAG, "获取运动汇总数据:  步数:" + sData.steps + " ,卡路里: " + sData.cal + " \n");
        }
        steps = String.valueOf(sData.steps);
        calorie = String.valueOf(sData.cal);

        //距离是根据系数算出来的，举例：男人系数：0.415，女人系数：0.413 步长=身高*系数 距离=步长*步数
        double kilo = sData.steps * Double.parseDouble(user.getHeight()) * rate / (100 * 1000);
        kilo = Math.floor(kilo * 100) / 100;//手环中没有四舍五入
        kilometer = String.format("%.2f", kilo);
        resetTabValue();
        PreferenceHelper.putString("currentData", steps + "@" + kilometer + "@" + calorie);
    }

    private void resetTabValue() {
        switch (currentIndex) {
            case 0:
                tv_type_value.setText(steps + "步");
                break;
            case 1:
                tv_type_value.setText(kilometer + "公里");
                break;
            case 2:
                tv_type_value.setText(sleep + "小时");
                break;
            case 3:
                tv_type_value.setText(calorie + "千卡");
                break;
            default:
                break;
        }
        tv_tab_steps.setText(steps);
        tv_tab_distance.setText(kilometer);
        tv_tab_sleep.setText(sleep);
        tv_tab_calorie.setText(calorie);
    }

    /**
     * 设置个人信息到手环中
     * 0 男 1 女
     */
    private void syncPersonData() {
        try {
            final String[] values = user.getBirthday().split("-");
            final int sex = "1".equals(user.getSex()) ? 0 : 1;
            final int height = (int) Float.parseFloat(user.getHeight());
            final int weight = (int) Float.parseFloat(user.getWeight());

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothLeService.SynPersonData(sex,
                            Integer.parseInt(values[0]),
                            Integer.parseInt(values[1]),
                            Integer.parseInt(values[2]),
                            height,
                            weight);
                    LogUtil.e(TAG, "设置 个人信息:生日：" + user.getBirthday() + "性别：" + user.getSex() + "身高和体重：" + user.getHeight() + ">>" + user.getWeight());
                }
            }, 800);
        } catch (Exception e) {
            mBluetoothLeService.SynPersonData(0, 1968, 10, 1, 175, 70);
        }
    }

    private String showResult(byte res) {
        String s = "";
        switch (res) {
            case 0:
                s = "成功";
                break;

            case 1:
                s = "失败";
                break;

            case 2:
                s = "非法命令";
                break;

            default:
                s = String.format("%x", res);
                break;
        }

        return s;

    }

    @Override
    public void handleActionSuccess(String actionName, Object object) { //历史记录
        if (FLAG_BRACELET.equals(actionName)) {
            DataDetailExtra extra = (DataDetailExtra) object;
            List<DataDetails> tempList = extra.getDeviceData();
            if (tempList != null) {
                dataDetailsList.clear();
                dataDetailsList.addAll(tempList);
                /*if((TextUtils.isEmpty(PreferenceHelper.getString("currentSleepData","")) && PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false) ||
                        (Double.parseDouble(sleep) == 0 && PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false)))){
                    DataDetails model = tempList.get(3);
                    if(model !=null){
                        ArrayList<String> list = model.getyValue();
                        if(list != null){
                            int lastYvaluesIndex = 0;
                            if(list.size() > 1){
                                lastYvaluesIndex = list.size()- 1;
                                sleep =  TextUtils.isEmpty(list.get(lastYvaluesIndex)) ? "0": list.get(lastYvaluesIndex);
                                if(Double.parseDouble(sleep) > 0){
                                    lastYvaluesIndex = list.size()-1;
                                }else{
                                    lastYvaluesIndex = list.size()-2;
                                }
                                sleep =  TextUtils.isEmpty(list.get(lastYvaluesIndex)) ? "0": list.get(lastYvaluesIndex);
                            }else{
                                sleep = "0";
                            }
                        }
                        PreferenceHelper.putString("currentSleepData", sleep);
                        tv_tab_sleep.setText(sleep);
                    }
                }*/
                refreshView(currentIndex);
            }
        } else if ("synchronization".equals(actionName)) {
            showToast("同步数据成功");
        } else if (FLAG_UPLOAD_SPORT.equals(actionName)) {
            if (object == null) {
                return;
            }
            try {
                String response = object.toString();
                if (response.endsWith("\r\n")) {
                    response = response.replace("\r\n", "");
                }
                JSONObject json = new JSONObject(response);
                boolean success = json.optBoolean("success");
                if (success) {
                    PreferenceHelper.putFistUploadSportData();//设置成手环已经同步过
                   /* showToast("同步数据成功");*/
                    // PreferenceHelper.clearFaildBraceletHistySportData();//上传成功则清空历史数据
                    //线形图  group  实例化
                    provider.requestDataDetailsnew2(deviceType,"column", pageno, pagesize, FLAG_BRACELET);
                } else {//失败的话，就去保存到本地
                    List<BralectModel> sportNewListDataFiald = sportHistoryData;
                    if (sportNewListDataFiald != null) {
                        PreferenceHelper.saveFaildBraceletHistorySporttData(sportNewListDataFiald);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                //失败的话，就去保存到本地
                List<BralectModel> sportNewListDataFiald = sportHistoryData;
                if (sportNewListDataFiald != null) {
                    PreferenceHelper.saveFaildBraceletHistorySporttData(sportNewListDataFiald);
                }
            }
        } else if (FLAG_UPLOAD_SLEEP.equals(actionName)) {//睡眠历史数据
            if (object == null) {
                return;
            }
            try {
                String response = object.toString();
                if (response.endsWith("\r\n")) {
                    response = response.replace("\r\n", "");
                }
                JSONObject json = new JSONObject(response);
                boolean success = json.optBoolean("success");
                if (success) {
                   /* showToast("同步数据成功");*/
                    PreferenceHelper.clearFaildBraceletSleepData();//上传成功则清空历史数据;同步请求数据
                    PreferenceHelper.putFistUploadSleepData();//设置成手环已经同步过
                    //线形图  group  实例化
                    provider.requestDataDetailsnew2(deviceType,"column", pageno, pagesize, FLAG_BRACELET);
                } else {//失败的话，就去保存到本地
                    List<SleepsData> sleepsDatasFaild = sleepsDatas;
                    if (sleepsDatasFaild != null) {
                        PreferenceHelper.saveFaildBraceletSleepData(sleepsDatasFaild);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                //失败的话，就去保存到本地睡眠历史数据
                List<SleepsData> sleepsDatasFaild = sleepsDatas;
                if (sleepsDatasFaild != null) {
                    PreferenceHelper.saveFaildBraceletSleepData(sleepsDatasFaild);
                }
            }
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        if (FLAG_UPLOAD_SPORT.equals(actionName)) {
            //失败的话，就去保存到本地
            List<BralectModel> sportNewListDataFaild = sportHistoryData;
            if (sportNewListDataFaild != null) {
                PreferenceHelper.saveFaildBraceletHistorySporttData(sportNewListDataFaild);
            }
        } else if (FLAG_UPLOAD_SLEEP.equals(actionName)) {
            //失败的话，就去保存到本地睡眠历史数据
            List<SleepsData> sleepsDatasFaild = sleepsDatas;
            if (sleepsDatasFaild != null) {
                PreferenceHelper.saveFaildBraceletSleepData(sleepsDatasFaild);
            }
        }

    }

    public void refreshView(int radiobuttonResId) {
        int position = 0;
        switch (radiobuttonResId) {
            case 0://第1个选项卡：步数
                position = 1;
                break;
            case 1://第2个选项卡：距离
                position = 4;
                break;
            case 2://第3个选项卡：睡眠
                position = 3;
                break;
            case 3://第4个选项卡：卡路里
                position = 0;
                break;
        }
        if (dataDetailsList.size() <= 0) {
            return;
        }

        tv_unit.setText("单位:  " + dataDetailsList.get(position).getUnit());
        yValue.clear();
        xValues = dataDetailsList.get(position).getxValue();
        yValues = dataDetailsList.get(position).getyValue();

        ArrayList<String> y_array = dataDetailsList.get(position).getY_array();
        float max ;
        max = ByteUtils.getMaxFromList(yValues)==0? Float.parseFloat(y_array.get(y_array.size() - 1)): ByteUtils.getMaxFromList(yValues);
        float min = Float.parseFloat(y_array.get(0));
        if (position == 2) {
            max = max / 3600f;
            for (int i = 0; i < yValues.size(); i++) {
                if (!TextUtils.isEmpty(yValues.get(i))) {
                    try {
                        //保留两位小数的另一种方法：Math.round( value * 100 ) / 100.0
                        yValue.add((float) Math.round(Float.parseFloat(yValues.get(i))));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    yValue.add(Float.valueOf(0));
                }
            }
        } else {
            for (int i = 0; i < yValues.size(); i++) {
                if (!TextUtils.isEmpty(yValues.get(i))) {
                    try {
                        yValue.add(Float.parseFloat(yValues.get(i)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    yValue.add(Float.valueOf(0));
                }
            }
        }
//		rl_broken_line_bg.removeAllViews();
//		rl_broken_line_bg.addView(new BrokenLineBackground(this, y_array, goalPosition));
        rl_broken_line.removeAllViews();
        rl_broken_line.addView(new BrokenLine(this, xValues, yValue, max, min, y_array.size(), Integer.parseInt(goal)));
    }

    /**
     * 获取新历史数据（运动详情）
     *
     * @return
     */
    private void getSportListData() {
        if (sportsDatas.size() == 0) {
            return;//返回空集合
        }
        List<BralectModel> mSportNewListData = new ArrayList<BralectModel>();
        long startTime = sportsDatas.get(0).time_stamp * 1000;
        int startSteps = sportsDatas.get(0).steps;
        int startCalories = sportsDatas.get(0).cal;

        if (sportsDatas.size() == 1) {
            BralectModel bralectModel = new BralectModel();
            bralectModel.setCalorie(BigDecimalUtils.transForLateNum(startCalories / 1000));
            bralectModel.setSteps(String.valueOf(startSteps));
            bralectModel.setTimeStamp(String.valueOf(startTime));
            //计算步数
            String distance = String.format("%.2f", startSteps * Double.parseDouble(PreferenceHelper.getUser().getHeight()) * rate / (100 * 1000));
            bralectModel.setDistance(distance);
            mSportNewListData.add(bralectModel);
        } else {
            for (int i = 1; i < sportsDatas.size(); i++) {
                if (DateUtil.isSameDayOfMillis(startTime, sportsDatas.get(i).time_stamp * 1000)) {//判断是同一天
                    startSteps += sportsDatas.get(i).steps;
                    startCalories += sportsDatas.get(i).cal;
                    if (i == sportsDatas.size() - 1) {
						/*addList(list,startTime, startSteps, startCalories);*/
                        BralectModel bralectModel = new BralectModel();
                        bralectModel.setCalorie(BigDecimalUtils.transForLateNum(startCalories / 1000));
                        bralectModel.setSteps(String.valueOf(startSteps));
                        bralectModel.setTimeStamp(String.valueOf(startTime));
                        //计算步数
                        String distance = String.format("%.2f", startSteps * Double.parseDouble(PreferenceHelper.getUser().getHeight()) * rate / (100 * 1000));
                        bralectModel.setDistance(distance);
                        mSportNewListData.add(bralectModel);
                    }
                } else {
					/*addList(list,startTime, startSteps, startCalories);*/
                    BralectModel bralectModel = new BralectModel();
                    bralectModel.setCalorie(String.valueOf(BigDecimalUtils.transForLateNum(startCalories / 1000)));
                    bralectModel.setSteps(String.valueOf(startSteps));
                    bralectModel.setTimeStamp(String.valueOf(startTime));
                    //计算步数
                    String distance = String.format("%.2f", startSteps * Double.parseDouble(PreferenceHelper.getUser().getHeight()) * rate / (100 * 1000));
                    bralectModel.setDistance(distance);
                    mSportNewListData.add(bralectModel);
                    // 重置startSteps
                    startSteps = sportsDatas.get(i).steps;
                    startCalories = sportsDatas.get(i).cal;
                    startTime = sportsDatas.get(i).time_stamp * 1000;
                }

            }
        }
        if (PreferenceHelper.getFaildBraceletHisrySportData() != null) {//如果由于历史数据，则一起上传
            mSportNewListData.addAll(PreferenceHelper.getFaildBraceletHisrySportData());
        }
        sportHistoryData = mSportNewListData;
        //PreferenceHelper.saveFaildBraceletHistorySporttData1(sportHistoryData);
        final String json = new Gson().toJson(mSportNewListData);
        provider.addbraceletSportData(json, FLAG_UPLOAD_SPORT);
    }

    /***
     * 第一次进入开始连接蓝牙
     *
     * @param isPullToRefresh 是否是下拉刷新
     */
    private void startConnectBooth(boolean isPullToRefresh) {
        sleepsDatas.clear();
        sportsDatas.clear();
        if (mBluetoothLeService != null && BluetoothLeService.isConnected) {//进行读取数据
            mBluetoothLeService.getSportDataTotal();//仿照下拉刷新时的做法，进行参照，如果已经连接进行获取数据
            if (isPullToRefresh) {//下拉刷新是的一些特殊操作
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(CLISEREFRESHED);
                    }
                }, 3000);
            }

        } else {
            if (!TextUtils.isEmpty(PreferenceHelper.getString(PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, ""))) {//地址为空if(已经有绑定的设备)
                if (PreferenceHelper.getBoolean(PreferenceHelper.BLUETOOTH_IS_BING, false)) {
                    if (!BluetoothLeService.isConnected) {
                        scanBLE(false);
                        String deviceName = PreferenceHelper.getString(PreferenceHelper.BLUETOOTH_DEVICE_NAME, "");
                        if (mBluetoothLeService != null) {
                            mBluetoothLeService.real_close();
                        }
                        if (deviceName.contains("T")) {
                            BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28T);
                        } else if (deviceName.contains("S")) {
                            BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28S);
                        }
                        if (isPullToRefresh) {//下拉刷新是的一些特殊操作
                            if (!adapter.isEnabled()) {//如果没有进行蓝牙连接，则开启蓝牙进行连接
                                adapter.enable();
								/*Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
								startActivityForResult(mIntent, 1);*/
                            }
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.sendEmptyMessage(CLISEREFRESHED);
                                }
                            }, 3000);
                        }
                        currentType = TYPE_BIND;
                        Message msg = Message.obtain();
                        msg.what = AUTO_CONNECT;
                        if (adapter.isEnabled()) {
                            mHandler.sendMessageDelayed(msg, 200);
                        } else {
                            mHandler.sendMessageDelayed(msg, 1000);
                        }
                        mHandler.removeMessages(SCAN_TIMEOUT);
                    } else {
                        tv_bluetooth.setText("(已连接)");
                    }
                }
            } else {
                if (!isPullToRefresh) {
                    showToast("请绑定设备");
                } else {
                    if (mBluetoothLeService != null) {
                        mBluetoothLeService.getWatchId();
                    }
                    mPullRefreshScrollView.onRefreshComplete();
                }
            }
        }
    }

    /***
     * 手环自动断开时的一些操作
     ***/
    private void setFlagBraceletNodata() {
        tv_bluetooth.setText("(未连接)");
        BluetoothLeService.isConnected = false;
        if (isFinishing()) {
            unbindService(mServiceConnection);
            mBluetoothLeService = null;
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        super.handleActionStart(actionName, object);
        hideLoading();
    }

    /**
     * 设置初始化的目标值（默认值）
     */
    private void setInitGoalValues(){
        mBluetoothLeService.setGoalSteps(8000);
        mBluetoothLeService.setGoalCal(350);
        mBluetoothLeService.setGoalDis(5);
    }
}
